package com.waimai.mobile.ui.activity;

import android.text.InputType;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.waimai.mobile.R;
import com.waimai.mobile.api.WaiMaiServer;
import com.waimai.mobile.api.entity.User;
import com.waimai.mobile.api.model.ResponseModel;
import com.waimai.mobile.ui.WaiMaiApp;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.TextChange;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.rest.RestService;


import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * Created by lin on 2015/6/15.
 */

@EActivity(R.layout.activity_regist)
public class RegistActivity extends BaseActivity02{

    private int currentStep = 1;
    private String phoneStr;

    @App
    public WaiMaiApp app;

    @ColorRes(R.color.main)
    public int mainColor;

    @ViewById(R.id.inputValidateCodeTv)
    public TextView inputValidateCodeTv;

    @ViewById(R.id.inputPasswordTv)
    public TextView inputPasswordTv;

    @ViewById(R.id.inputMsgEdt)
    public EditText inputMsgEdt;

    @ViewById(R.id.registBtn)
    public Button registBtn;

    @RestService
    public WaiMaiServer server;

    @AfterInject
    public void afterInject(){
        server.setHeader("Content-Type", "application/json");
        setupSMSSDK();
    }

    @AfterViews
    public void afterViews(){
        setActionBarTitle("注册");
    }

    @TextChange(R.id.inputMsgEdt)
    public void onInputMsgTextChanged(TextView edt){
        String msg = edt.getText().toString().trim();
        switch (currentStep){
            case 1:
                if(msg != null && msg.length() == 11){
                    registBtn.setEnabled(true);
                }else{
                    registBtn.setEnabled(false);
                }
                break;
            case 2:
                if(msg != null && msg.length() == 4){
                    registBtn.setEnabled(true);
                }else{
                    registBtn.setEnabled(false);
                }
                break;
            case 3:
                if(msg != null && msg.length() >= 6 && msg.length() <= 16){
                    registBtn.setEnabled(true);
                }else{
                    registBtn.setEnabled(false);
                }
                break;
        }
    }

    @Click(R.id.registBtn)
    public void registBtnClick(){
        String msgStr = inputMsgEdt.getText().toString().trim();
        switch (currentStep) {
            case 1:
                step1(msgStr);
                break;
            case 2:
                step2(msgStr);
                break;
            case 3:
                step3(msgStr);
                break;
        }
    }

    public void step1(String phone){
        checkPhoneRequest(phone);
    }

    public void step2(String validateCode){
        SMSSDK.submitVerificationCode("86", phoneStr, validateCode);
    }

    @UiThread
    public void step3(String password){
        User user = new User(phoneStr, phoneStr, password);
        System.out.println(user);
        submitRegistRequest(user);
    }

    @Background
    public void checkPhoneRequest(String phone){
        try {
            ResponseModel<User> model = server.regist(new User(phone));
            if(model != null){
                switch (model.getStatus().getStatusCode()) {
                    case ResponseModel.STATUS_REGIST_PHONE_EXTIST:
                        phoneExisted();
                        break;
                    case ResponseModel.STATUS_REGIST_PHONE_AVALIABLE:
                        SMSSDK.getVerificationCode("86", phone);
                        break;
                    case ResponseModel.STATUS_SERVER_ERROR:
                        serverError();
                        break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            netError();
        }
    }

    @UiThread
    public void phoneExisted(){
        Toast.makeText(getApplicationContext(), "手机号已存在，请直接登录", Toast.LENGTH_SHORT).show();
    }

    @UiThread
    public void getValidateCodeSuccess(){
        System.err.println("获取验证码成功-----------------------");
        SMSSDK.unregisterEventHandler(getValidateHandler);
        Toast.makeText(getApplicationContext(), "验证码已发送", Toast.LENGTH_SHORT).show();
        phoneStr = inputMsgEdt.getText().toString().trim();

        inputValidateCodeTv.setTextColor(mainColor);
        inputMsgEdt.setText("");
        inputMsgEdt.setHint("请输入手机接收到的验证码");
        registBtn.setText("提交验证码");
        currentStep = 2;
    }

    @UiThread
    public void getValidateCodeFailed(){
        System.err.println("获取验证码失败-----------------------");
        Toast.makeText(getApplicationContext(), "网络错误，请重试", Toast.LENGTH_SHORT).show();
    }

    @UiThread
    public void submitValidateCodeSuccess(){
        System.err.println("验证码正确-----------------------");
        SMSSDK.unregisterEventHandler(submitValidateHandler);
        Toast.makeText(getApplicationContext(), "验证成功", Toast.LENGTH_SHORT).show();

        inputPasswordTv.setTextColor(mainColor);
        inputMsgEdt.setText("");
        inputMsgEdt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        inputMsgEdt.setHint("请设置密码(6-16位)");
        registBtn.setText("注册");
        currentStep = 3;
    }

    @UiThread
    public void submitValidateCodeFailed(){
        System.err.println("验证码错误-----------------------");
        Toast.makeText(getApplicationContext(), "验证码错误或已过期，请重新发送验证码", Toast.LENGTH_SHORT).show();
    }

    private EventHandler getValidateHandler = null;
    private EventHandler submitValidateHandler = null;
    public void setupSMSSDK(){
        SMSSDK.initSDK(this, "822367ce1afc", "cf704b10100931e34b929eb8506c0c70");
        getValidateHandler = new EventHandler(){

            @Override
            public void afterEvent(int event, int result, Object data) {

                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
                        System.out.println(data);

                    }else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
                        //获取验证码成功
                        getValidateCodeSuccess();
                    }else if (event ==SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){
                        //返回支持发送验证码的国家列表
                    }
                }else{
                    System.out.println(data.getClass());
                    ((Throwable)data).printStackTrace();
                    getValidateCodeFailed();
                }
            }
        };

        submitValidateHandler = new EventHandler(){

            @Override
            public void afterEvent(int event, int result, Object data) {

                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
                        submitValidateCodeSuccess();
                    }else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
                        //获取验证码成功
                    }else if (event ==SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){
                        //返回支持发送验证码的国家列表
                    }
                }else{
                    ((Throwable)data).printStackTrace();
                    submitValidateCodeFailed();
                }
            }
        };
        SMSSDK.registerEventHandler(getValidateHandler);
        SMSSDK.registerEventHandler(submitValidateHandler);
    }


    @Background(id="registRequest")
    public void submitRegistRequest(User user){
        try {
            ResponseModel<User> model = server.regist(user);
            System.out.println(model);
            if(model != null){
                switch (model.getStatus().getStatusCode()) {
                    case ResponseModel.STATUS_REGIST_SUCCESS:
                        registSuccess(model.getData());
                        break;
                    case ResponseModel.STATUS_REGIST_FAILED:
                        registFailed();
                        break;
                    case ResponseModel.STATUS_SERVER_ERROR:
                        serverError();
                        break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            netError();
        }
    }

    @UiThread
    public void registSuccess(User user){
        app.setUser(user);
        Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_SHORT).show();
        onBackPressed();
        finish();
    }

    @UiThread
    public void registFailed(){
        Toast.makeText(getApplicationContext(), "手机号已存在，请直接登录", Toast.LENGTH_SHORT).show();
    }

    @UiThread
    public void netError(){
        Toast.makeText(getApplicationContext(), "网络错误，请重试", Toast.LENGTH_SHORT).show();
    }

    @UiThread
    public void serverError(){
        Toast.makeText(getApplicationContext(), "服务器异常，请重试", Toast.LENGTH_SHORT).show();
    }
}
